package com.bwie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.Es.EsGoods;
import com.bwie.pojo.Goods;
import com.bwie.pojo.Image;
import com.bwie.pojo.Linkage;
import com.bwie.service.GoodsService;
import com.bwie.service.ImageService;
import com.bwie.service.LinkageService;
import com.bwie.unit.R;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("user")
public class GoodsController {

    /**
     * 列表接口
     */
    @Autowired
    private GoodsService goodsService;

    /**
     * 下拉框接口
     */
    @Autowired
    private LinkageService linkageService;

    /**
     * 收藏接口
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private ImageService imageService;

    /**
     * 列表查询
     * @param goods
     * @return
     */
    @PostMapping("PageList")
    public R PageList(@RequestBody Goods goods){
        Page<Goods> goodsPage = new Page<>(goods.getPageNum(), goods.getPageSize());
        Page<Goods> list = goodsService.pageList(goodsPage);
        return R.OK(list);
    }

    /**
     * 添加功能
     */
    @PostMapping("addGoods")
    public R addGoods(@RequestBody Goods goods){
        //自动添加创建时间
        goods.setGoodsCreatetime(new Date());
        String s = RandomUtil.randomNumbers(4);
        //自动添加货物货号
        goods.setGoodsNumber("Dj"+s);
        goodsService.save(goods);
        for (Image image : goods.getImageList()) {
            image.setGoodsId(goods.getId());
            imageService.save(image);
        }
        return R.OK();
    }
    /**
     * 获取三级联动下拉框
     * @return
     */
    @PostMapping("getLinkageList/{id}")
    public R getLinkageList(@PathVariable Integer id){
        LambdaQueryWrapper<Linkage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Linkage::getLinkageId,id);
        List<Linkage> list = linkageService.list(wrapper);
        return R.OK(list);
    }

    /**
     * 收藏方法
     */
    @PostMapping("getCollection/{id}")
    public R getCollection(@PathVariable Integer id){
        Boolean text = stringRedisTemplate.opsForSet().isMember("text", id.toString());
        if (text){
            stringRedisTemplate.opsForSet().remove("text",id.toString());
            return R.OK("暂无收藏");
        }else {
            stringRedisTemplate.opsForSet().add("text",id.toString());
            return R.OK("收藏成功");
        }
    }

    @PostMapping("createEs")
    public R createEs(){
        goodsService.createEs();
        return R.OK();
    }

    //es列表
    @PostMapping("EsPage")
    public R EsPage(@RequestBody Goods goods){
        //模糊查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (!StringUtils.isEmpty(goods.getThreename())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("threename",goods.getThreename()));
        }

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("threename").preTags("<font color='green'>").postTags("</font>");

        //分页
        int pageNum = 0;
        if (goods.getPageNum()>0){
            pageNum = goods.getPageNum()-1;
        }
        PageRequest of = PageRequest.of(pageNum, goods.getPageSize());

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder)
                .withHighlightBuilder(highlightBuilder)
                .withPageable(of);
        SearchHits<EsGoods> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsGoods.class);
        long total = search.getTotalHits();
        ArrayList<EsGoods> list = new ArrayList<>();
        for (SearchHit<EsGoods> esGoodsSearchHit : search) {
            EsGoods content = esGoodsSearchHit.getContent();
            List<String> threename = esGoodsSearchHit.getHighlightField("threename");
            if (threename!=null && threename.size()>0){
                String s = threename.get(0);
                content.setThreename(s);
            }
            list.add(content);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("pageNum",pageNum);
        map.put("pageSize",goods.getPageSize());
        map.put("list",list);
        return R.OK(map);
    }
}
